package cn.cjy.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JDBCConfig {
	private static Connection conn;
	
	private static String driverClass;
	
	private static String url;
	
	private static String username;
	
	private static String password;
	
	
	static {
		try {
			readConfig();
			Class.forName(driverClass);
			conn=DriverManager.getConnection(url, username, password);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("鏁版嵁搴撻摼鎺ュけ璐�");
		}
		
		
		
	}
	
	private static void readConfig() throws IOException {
		InputStream in=JDBCConfig.class.getClassLoader().getResourceAsStream("db.properties");
		Properties pro=new Properties();
		pro.load(in);
		driverClass=pro.getProperty("jdbc.driver");
		url=pro.getProperty("jdbc.url");
		username=pro.getProperty("jdbc.username");
		password=pro.getProperty("jdbc.psw");
		//password=pro.getProperty("jdbc.password");
	}
	public static Connection getConnection() {
		
		return conn;
	}
	/**
	 * 关闭所有连接
	 * @param conn
	 * @param stm
	 * @param rs
	 */
	public static void closeAll(Connection conn,Statement stm,ResultSet rs){
		try {
			if (rs!=null){
				rs.close();
				rs=null;
			}
			if (stm !=null){
				stm.close();
				stm=null;
			}
			if (conn !=null){
				conn.close();
				conn=null;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static void main(String [] args) {
		Connection conn =JDBCConfig.getConnection();
		if(conn!=null) {
			System.out.println("数据库链接成功");
		}else {
			System.out.println("数据库链接不成功");
		}
	}

}
